package com.kuang.config;

import com.kuang.pojo.User;
import com.kuang.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权=======>principalCollection");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();

        User currentUser = (User) subject.getPrincipal();

        info.addStringPermission(currentUser.getPerms());


        return info;


    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证======>authenticationToken");


        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //假设用户名和密码
//        String username = "root";
//        String password = "123456";


        //连接数据库
        User user = userService.queryUserByName(token.getUsername());
        //判断用户是否存在
        if (user == null) {
            return null;        //抛出UnknownAccountException
        }


        //登录成功 往session中存储user信息
        Subject currentUser = SecurityUtils.getSubject();

        currentUser.getSession().setAttribute("user",currentUser);


        return new SimpleAuthenticationInfo(user, user.getPwd(), "");

    }
}
